package com.fhz.a2102mvi

import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.activity.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.flowWithLifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.fhz.a2102mvi.entity.BannerEntity
import com.fhz.a2102mvi.intent.BannerIntent
import com.fhz.a2102mvi.uistate.BannerUIState
import com.fhz.a2102mvi.viewmodel.MainViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch


@AndroidEntryPoint
class MainActivity : AppCompatActivity() {

    private lateinit var textView : TextView
    private lateinit var click : Button
    val viewMdoel:MainViewModel by viewModels()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

//        textView.text = "1"
        textView =  findViewById<TextView>(R.id.abc_abc)
        click =  findViewById(R.id.insertClick)



        click.setOnClickListener{
            lifecycleScope.launch{
                val bannerEntity = BannerEntity(1,"",1,"title",1,"12")
                viewMdoel.insertBanner(bannerEntity)
            }
        }


        lifecycleScope.launch{
            repeatOnLifecycle(Lifecycle.State.STARTED){ //最推荐的一种
                viewMdoel.uiState.collect{
                    when(it){
                        is BannerUIState.Success -> {
                            updateUI(it)
                        }
                        is BannerUIState.Fail -> {
                             println("失败")
                        }
                        is BannerUIState.Loading -> {
                             println("控制进度条")
                        }
                    }
                }
            }
        }

//        banner.setOnClickerListner{
//            viewMdoel.channels.send(BannerIntent.ClickBanner)
//        }


    }

    private fun updateUI(it: BannerUIState.Success) {
        //更新适配器的数据
        println("成功!")
        println(it)


        if(it.banner == null){
            return
        }

        it.banner?.data?.list?.get(0)?.title.apply {
            println(this)
            println("134")
            textView.text = this

        }
    }


    fun click(view: View) {
        lifecycleScope.launch{
            viewMdoel.channels.send(BannerIntent.GetBannerList)
        }


    }


}